package com.example.controller;
import cn.hutool.captcha.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * @Description: 验证码Servlet
 * @Date: 2022/10/19 11:38
 * @Author: SinkDream
 */
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(80,30,4,15);
        lineCaptcha.setFont(new Font("文泉驿正黑", Font.ITALIC | Font.BOLD, 26));
        // 重新生成code
        lineCaptcha.createCode();
        //得到code
        String code = lineCaptcha.getCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER",code);
        ServletOutputStream sos = response.getOutputStream();
        lineCaptcha.write(sos);
        sos.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
